from fastapi import APIRouter, Depends, Query
from schema.resp import RestfulModel
from dependencies import get_mongo_db_of_condition_safety
from pymongo.database import Database
import re




condition_safety_car_information_router = APIRouter(prefix='/condition_safety', tags=['车辆状态安全-车辆信息展示'])


class MongoCollectionName:
    """
    mongo 中 collection 的 name 常量
    """
    CAR_INFORMATION_SAMPLE = 'Car_information_sample'


#获取车辆信息列表 /vehicle_status/list
#请求参数：keywords page size
#total_page 总页数
#total_count 总记录数
#docs
@condition_safety_car_information_router.get('/list',summary='车辆信息列表')
async def get_car_info(page=1,size=8,vin='',mongo_db: Database = Depends(get_mongo_db_of_condition_safety)):
    car_data_col = mongo_db[MongoCollectionName.CAR_INFORMATION_SAMPLE]
    if vin=='':
        cursor = car_data_col.find({}, {'_id': 0})
        data = []
        for u in cursor:
            data.append(u)
    else:
        cursor = car_data_col.find({'VIN':re.compile(vin)},{'_id': 0})
        data = []
        for u in cursor:
            data.append(u)

    total_count = len(data)
    total_page = int((total_count + int(size) - 1) / int(size))
    docs = data[(int(page) - 1) * int(size):int(page) * int(size)]
    result = {
        'total_page': total_page,
        'total_count': total_count,
        'docs': docs
    }
    return RestfulModel.success(result)



@condition_safety_car_information_router.get('/list-v2', summary='车辆信息列表 - v2')
async def get_car_info_v2(page: int = Query(1, gt=0),
                          size: int = Query(8, gt=0),
                          vin: str = Query(''),
                          mongo_db: Database = Depends(get_mongo_db_of_condition_safety)):
    car_data_col = mongo_db[MongoCollectionName.CAR_INFORMATION_SAMPLE]
    offset = (page - 1) * size
    find_filter = {}
    if vin != '':
        find_filter['VIN'] = re.compile(vin)
    total_count = car_data_col.count_documents(filter=find_filter)
    total_page = int((total_count + size - 1) / size)
    cursor = car_data_col.find(find_filter, skip=offset, limit=size)
    docs = list(cursor)
    result = {
        'total_page': total_page,
        'total_count': total_count,
        'docs': docs
    }
    return RestfulModel.success(result)
    

